﻿using DevComponents.AdvTree;
using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    public partial class RoleMgr : XtraForm
    {
        private Dictionary<long, List<long>> m_Dic = new Dictionary<long,List<long>> ();
        public RoleMgr()
        {
            InitializeComponent();
        }

        private void RoleMgr_Load(object sender, EventArgs e)
        {
            RefreshRoleTree();
            RefreshActionTree();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            foreach (Node node in advTreeAction.Nodes)
                list.Add(node.Text);
            ActionForm form = new ActionForm();
            form.IsAdd = true;
            form.NameList = list;
            if (DialogResult.OK == form.ShowDialog())
            {
                string name = form.Name;
                string sql = "insert into HS_SECU_ROLE (NAMES) values '" + name + "'";
                try
                {
                    bool isSuccess = DB2Helper.CreateInstance().DoDB2Execute(new string[] { sql });
                    if (!isSuccess)
                    {
                        MessageBox.Show(this, "插入角色名称失败！");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.error("插入角色名称异常：" + ex.Message);
                    MessageBox.Show(this, "插入角色名称异常：" + ex.Message);
                    return;
                }
                MessageBox.Show(this, "新增角色成功！");
                RefreshRoleTree();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
             Node selectedNode = this.advTreeRole.SelectedNode;
             if (selectedNode == null)
                 return;
             if (selectedNode == rootRoleNode)
             {
                 MessageBox.Show(this, "根节点不能删除");
                 return;
             }
             try
             {
                 long roleId = long.Parse(selectedNode.Tag.ToString());

                 List<string> list = new List<string>();
                 list.Add("delete from HS_SECU_ROLE_ACTION where Role_id = " + roleId);
                 list.Add("delete from HS_SECU_ROLE where Id = " + roleId);
                 if (!DB2Helper.CreateInstance().DoDB2Execute(list.ToArray()))
                 {
                     MessageBox.Show(this, "删除角色失败");
                     return;
                 }
             }
             catch (Exception ex)
             {
                 LogHelper.error("删除角色异常：" + ex.Message);
                 MessageBox.Show(this, "删除角色异常：" + ex.Message);
                 return;
             }
             MessageBox.Show(this, "删除角色成功");
             RefreshRoleTree();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            m_Dic.Clear();
            foreach (Node role in rootRoleNode.Nodes)
            {
                if (role.CheckState == CheckState.Checked)
                {
                    List<long> actionIdList = new List<long>();
                    foreach (Node action in rootActionNode.Nodes)
                    {
                        if (action.CheckState == CheckState.Checked)
                            actionIdList.Add(long.Parse(action.Tag.ToString()));
                    }
                    m_Dic.Add(long.Parse(role.Tag.ToString()), actionIdList);
                }
            }
            if (m_Dic.Count == 0)
                return;
            try
            {
                List<string> list = new List<string>();
                foreach (long roleId in m_Dic.Keys)
                {
                    list.Add("delete from HS_SECU_ROLE_ACTION where Role_id = " + roleId);
                    foreach (long actionId in m_Dic[roleId])
                        list.Add("insert into HS_SECU_ROLE_ACTION (ROLE_ID, ACTION_ID) values (" + roleId + "," + actionId + ")");
                }
                if (!DB2Helper.CreateInstance().DoDB2Execute(list.ToArray()))
                {
                    MessageBox.Show(this, "保存失败");
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("保存角色操作异常：" + ex.Message);
                MessageBox.Show("保存异常：" + ex.Message);
                return;
            }     
            MessageBox.Show("保存成功！");
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void RefreshRoleTree()
        {
            DataTable dt = RefreshRoleData();
            if (dt == null || dt.Rows.Count == 0)
                return;
            rootRoleNode.Nodes.Clear();
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Node node = new Node();
                    node.CheckBoxVisible = true;
                    node.CheckState = CheckState.Unchecked;
                    node.Text = dr["names"].ToString();
                    node.Tag = long.Parse(dr["id"].ToString());
                    rootRoleNode.Nodes.Add(node);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("加载角色树节点异常：" + ex.Message);
                MessageBox.Show("加载角色树节点异常：" + ex.Message);
            }
        }

        private void RefreshActionTree()
        {
            DataTable dt = RefreshActionData();
            if (dt == null || dt.Rows.Count == 0)
                return;
            rootActionNode.Nodes.Clear();
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Node node = new Node();
                    node.CheckBoxVisible = true;
                    node.CheckState = CheckState.Unchecked;
                    node.Text = dr["name_"].ToString();
                    node.Tag = long.Parse(dr["id"].ToString());
                    rootActionNode.Nodes.Add(node);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("加载操作树节点异常：" + ex.Message);
                MessageBox.Show("加载操作树节点异常：" + ex.Message);
            }
        }

        //刷新列表操作
        private DataTable RefreshRoleData()
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "select * from HS_SECU_ROLE order by ID";
                dt = DB2Helper.CreateInstance().DoDB2Select(sql);
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新角色信息异常：" + ex.Message);
                MessageBox.Show("刷新角色信息异常：" + ex.Message);
                return null;
            }
            return dt;
        }

        private DataTable RefreshRoleActionData(long roleId)
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "select * from HS_SECU_ROLE_ACTION where Role_id = " + roleId;
                dt = DB2Helper.CreateInstance().DoDB2Select(sql);
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新角色操作信息异常：" + ex.Message);
                MessageBox.Show("刷新角色操作信息异常：" + ex.Message);
                return null;
            }
            return dt;
        }

        //刷新列表操作
        private DataTable RefreshActionData()
        {
            DataTable dt = new DataTable();
            try
            {
                string sql = "select * from HS_ACTION order by ID";
                dt = DB2Helper.CreateInstance().DoDB2Select(sql);
            }
            catch (Exception ex)
            {
                LogHelper.error("刷新操作功能信息异常：" + ex.Message);
                MessageBox.Show("刷新操作功能信息异常：" + ex.Message);
                return null;
            }
            return dt;
        }

        //角色节点变化是对应的操作也相应变化，
        private void advTreeRole_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            Node selectedNode = advTreeRole.SelectedNode;
            if (selectedNode == null || selectedNode == rootRoleNode)
            {
                foreach (Node child in rootActionNode.Nodes)
                    child.Checked = false;
                return;
            }
            long roleId = long.Parse(selectedNode.Tag.ToString());
            //根据roleID获取勾选的操作
            DataTable dt = RefreshRoleActionData(roleId);
            if (dt == null || dt.Rows.Count == 0)
            {
                foreach (Node child in rootActionNode.Nodes)
                    child.Checked = false;
                return;
            }
            List<long> list = new List<long>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(long.Parse(dr["Action_Id"].ToString()));
            }
            foreach (Node child in rootActionNode.Nodes)
            {
                if (list.Contains(long.Parse(child.Tag.ToString())))
                    child.CheckState = CheckState.Checked;
                else
                    child.CheckState = CheckState.Unchecked;
            }
        }

        private void advTreeRole_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            //如果根节点打钩，下面的子节点都打钩
            if (e.Node == rootRoleNode)
            {
                if (e.Node.CheckState == CheckState.Checked)
                {
                    foreach (Node child in rootRoleNode.Nodes)
                    {
                        child.CheckState = CheckState.Checked;
                    }
                }
                else if (e.Node.CheckState == CheckState.Unchecked)
                {
                    foreach (Node child in rootRoleNode.Nodes)
                    {
                        child.CheckState = CheckState.Unchecked;
                    }
                }
            }
            else
            {
                int sum = 0;
                foreach (Node child in rootRoleNode.Nodes)
                {
                    if (child.CheckState == CheckState.Checked)
                        sum++;
                }
                if (sum == rootRoleNode.Nodes.Count)
                    rootRoleNode.CheckState = CheckState.Checked;
                else if (sum == 0)
                    rootRoleNode.CheckState = CheckState.Unchecked;
                else
                    rootRoleNode.CheckState = CheckState.Indeterminate;
            }
        }

        private void advTreeAction_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            //如果根节点打钩，下面的子节点都打钩
            if (e.Node == rootActionNode)
            {
                if (e.Node.CheckState == CheckState.Checked)
                {
                    foreach (Node child in rootActionNode.Nodes)
                    {
                        child.CheckState = CheckState.Checked;
                    }
                }
                else if (e.Node.CheckState == CheckState.Unchecked)
                {
                    foreach (Node child in rootActionNode.Nodes)
                    {
                        child.CheckState = CheckState.Unchecked;
                    }
                }
            }
            else
            {
                int sum = 0;
                foreach (Node child in rootActionNode.Nodes)
                {
                    if (child.CheckState == CheckState.Checked)
                        sum++;
                }
                if (sum == rootActionNode.Nodes.Count)
                    rootActionNode.CheckState = CheckState.Checked;
                else if (sum == 0)
                    rootActionNode.CheckState = CheckState.Unchecked;
                else
                    rootActionNode.CheckState = CheckState.Indeterminate;
            }
        }

    }
}
